package edu.school.controller;

import edu.school.entity.Admin;
import edu.school.entity.User;
import edu.school.service.AdminService;
import edu.school.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    AdminService adminService;
    @Autowired
    UserService userService;
    @RequestMapping("/toRegiste")
    public String toRegiste(){
        return "registe";
    }
    //登录功能
    /*@RequestMapping("/login")
    public String login(Admin admin, HttpServletRequest request, Model model){
        Admin a=new Admin();
        a.setUsername(admin.getUsername());
        a.setPwd(admin.getPwd());
        Admin record= adminService.login(a);
        if (admin != null) {
            request.getSession().setAttribute("admin", record);
            request.getSession().setAttribute("type", 2);
            return "redirect:/toMain";
        }
        model.addAttribute("msg","管理员用户名或者密码错误");
        return "login";
    }*/
    @RequestMapping("/login")
    public String login(String username,String pwd, Integer type,HttpSession session, Model model){
        if(type==1){
            User user=userService.login(username,pwd);
            if (user != null) {
                session.setAttribute("user", user);
                session.setAttribute("type", 1);
                User record=userService.findById(user.getId());
                model.addAttribute("record",record);
                return "common/main";
            }
            model.addAttribute("msg","用户名学号或者密码错误");
            return "login";

        }
        Admin admin=new Admin();
        admin.setUsername(username);
        admin.setPwd(pwd);
        Admin record= adminService.login(admin);
        if (admin != null) {
            session.setAttribute("admin", record);
            session.setAttribute("type", 2);
            return "redirect:/toMain";
        }
        model.addAttribute("msg","管理员用户名或者密码错误");
        return "login";
    }
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";

    }

    @RequestMapping("/toConsole")
    public String toConsole(){
        return "console";

    }

    @RequestMapping("/toMain")
    public String toMain(){
        return "main";

    }

    @RequestMapping("/loginout")
    public String loginout(HttpSession session){
        session.invalidate();
        return "login";

    }
}
